package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.query.UserQuery;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@Slf4j
@Api(tags = "用户管理接口")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    /**
     * 新增用户
     */
    @ApiOperation("新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userDTO){
        //1.把 DTO 拷贝到 PO
        User user = BeanUtil.copyProperties(userDTO, User.class);
        //2.新增
        userService.save(user);
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户接口")
    @DeleteMapping("/{id}")
    public void deleteUserById(@ApiParam("用户id") @PathVariable Long id){
        userService.removeById(id);
    }

    /**
     * 根据id查询用户
     */
    @ApiOperation("根据id查询用户接口")
    @GetMapping("/{id}")
    public UserVO QueryUserById(@ApiParam("用户id") @PathVariable Long id){
        return userService.queryUserAndAddressById(id);
    }

    /**
     * 根据id批量查询用户
     */
    @ApiOperation("根据id批量查询用户接口")
    @GetMapping
    public List<UserVO> QueryUserByIds(@ApiParam("用户id集合") @RequestParam("ids") List<Long> ids){
        return userService.queryUserAndAddressByIds(ids);
    }

    /**
     * 根据id扣减余额
     */
    @ApiOperation("根据id扣减余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deductionMoneyById(@ApiParam("用户id") @PathVariable Long id,
                                   @ApiParam("扣减的金额") @PathVariable Integer money){
        userService.deductionMoneyById(id,money);

    }


    /**
     * 根据复杂条件查询用户 lambda
     */
    @ApiOperation("根据复杂条件查询用户接口")
    @GetMapping("/list")
    public List<UserVO> queryUsers(UserQuery query){
        //1.查询用户PO集合
        List<User> userList = userService.queryUsers(query.getName(),query.getStatus(),query.getMinBalance(),query.getMaxBalance());
        //2.把PO拷贝到VO
        return BeanUtil.copyToList(userList, UserVO.class);
    }

    /**
     * 根据分页查询用户接口
     */
    @ApiOperation("根据分页查询用户接口")
    @GetMapping("/page")
    public PageDTO<UserVO> queryUsersPage(UserQuery query){
        return userService.queryUsersPage(query);
    }






}
